package com.lyd.office.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 描述 命令行工具
 *
 * @author liyadong
 * @date 2024-05-10 17:44
 */
@Slf4j
public class ProcessUtils {

    /**
     * 描述 执行命令
     * @param	command 命令
     * @author liyadong
     * @date 2024/5/10 17:45
     * @return java.lang.Integer
     */
    public static Integer exec(String command) {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("bash", "-c", command);
        try {
            Process process = processBuilder.start();
            // 读取输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info(line);
            }
            // 等待命令执行完成
            process.waitFor();
            // 获取退出值
            int exitValue = process.exitValue();
            log.info("命令执行结束，退出值: " + exitValue);
            process.destroy();
            return exitValue;
        } catch (IOException | InterruptedException e) {
            log.error("命令：{},执行失败：{}", command, e.getMessage());
        }
        return 0;
    }
}
